package com.rtp.transformer.fin.server;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.rtp.transformer.fin.client.model.AccountCategory;
import com.rtp.transformer.fin.server.util.HibernateUtil;
import com.rtp.transformer.parser.TXTOutAndInStream;
import com.rtp.transformer.parser.util.FormatUtil;

public class UploadImpl extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	response.setContentType("text/plain");
		
	FileItem uploadItem = getFileItem(request);
	if (uploadItem == null)
	{
		response.getWriter().write("NO-SCRIPT-DATA");
		return;
	}
	TXTOutAndInStream www = FormatUtil.getOutInStream("GeneralLedgerMonthlyDetailReport");
	try {
		List<AccountCategory> l = www.read(uploadItem.getInputStream());
		Session s = HibernateUtil.currentSession();
		Transaction t= s.beginTransaction();
		for (AccountCategory ac : l) {
			s.saveOrUpdate(ac);
		}
		t.commit();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
//	response.getWriter().write(new String(uploadItem.get()));
	}
	
	private FileItem getFileItem(HttpServletRequest request)
	{
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try
		{
			List  items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext())
			{
				FileItem item = (FileItem) it.next();
				if (!item.isFormField() && "file".equals(item.getFieldName()))
				{
					return item;
				}
			}
		}
		catch (FileUploadException e)
		{
			return null;
		}
		return null;
	}

}
